<template>
  <div class="page_root" :key="queryUpdateFlag" data-page-name="交付-模板项目延期项目" data-page-identification="p_i1csvomayu">
    <a-spin :spinning="pageLoading.loading" :tip="pageLoading.tip">
      <!-- begin vid_b0zuspst8g 自定义模板_uj2zmi94kj -->
      <a-modal :visible="state.changeDataVisible" title="修改原因" centered @ok="confirmReason" @cancel="cancelReason">
        <a-textarea v-model:value="state.changeReason" :rows="4" />
      </a-modal>
      <a-modal :visible="state.descriptionVisible" title="描述" centered @ok="confirmDescription" @cancel="cancelDescription">
        <a-textarea :rows="4" v-model:value="state.description" />
      </a-modal>
      <div class="body">
        <div class="title">
          <div class="top-title">水泥配料项目延期项目</div>
          <a-space>
            <div>表头含下划线的字段支持双击表格编辑详细内容</div>
            <a-button type="primary" @click="handleIssued" :loading="state.downLoading">下发</a-button>
            <!--                        <a-button type="primary" @click="handleShowDescription">描述</a-button>-->
          </a-space>
        </div>
        <div class="content">
          <div class="left">
            <div class="title-margin"> <div class="zb-img"></div>指标(截止至今日零点) </div>
            <div class="left-content">
              <div class="yq-div">
                <div class="title-content">延期项目总数</div>
                <div class="number red-color">{{ state.delayCount.count }}</div>
              </div>
              <div class="scroll-container">
                <div class="content-item" v-for="(item, idx) in state.projectData" :key="idx">
                  <div class="title-content" :title="item.title">{{ item.name }}</div>
                  <div class="number">{{ item.count }}</div>
                </div>
              </div>
            </div>
          </div>
          <!--                    <div class="right">-->
          <!--                        <div class="title-margin"> <div class="ms-img"></div>描述 </div>-->
          <!--                        <div class="description">{{state.description}}</div>-->
          <!--                    </div>-->
        </div>
        <div class="default-table">
          <a-table :columns="columns" :scroll="{ x: 'max-content', y: 520 }" :data-source="state.tableData" :pagination="false" bordered @resizeColumn="handleResizeColumn">
            <template #headerCell="{ column, title }">
              <template v-if="title == '原因说明'">
                <div class="text-line-div">{{ title }}</div>
              </template>
            </template>

            <template #bodyCell="{ record, text, column }">
              <template v-if="column.dataIndex === 'opration'">
                <a-button type="link" size="small" @click="showEdit(record)">编辑</a-button>
                <a-popconfirm title="确定要删除吗？" @confirm="handleDeleteFaq(record)">
                  <a-button type="link" size="small">删除</a-button>
                </a-popconfirm>
                <a-button type="link" size="small" @click="showPraise(record)">点赞</a-button>
              </template>
              <template v-if="column.dataIndex === 'reason'">
                <div class="db-click" @dblclick="changeData(record)">{{ text || '--' }}</div>
              </template>
            </template>
          </a-table>
        </div>
      </div>
      <!-- end vid_b0zuspst8g 自定义模板_uj2zmi94kj -->
    </a-spin>
  </div>
</template>
<script setup lang="tsx">
  import {
      h, ref, reactive, toRaw, markRaw, watch, computed,
      onBeforeMount, onMounted, onBeforeUnmount, onUnmounted, onActivated, onDeactivated
    } from "vue";
    import { useRoute, useRouter } from 'vue-router';
    const router = useRouter();
    const route = useRoute();
    import { get, post, put, del, request, requestWithHeaders } from '@/utils/http/Axios';
    import { cloneDeep, localGet, merge, getDifferenceArray, traversalTreeStructure, checkCaseCondition, renderStringInTemplate, handleBreadcrumbJump, throttle, permission, getComponentParamsValue } from '@/utils/index';
    import { isNullOrEmpty, isEmptyArr, isNullOrUnDef, isContained, isArray, isEmpty, isObject } from '@/utils/is';
    import dayjs from 'dayjs';
    import { getPagePcChartsDataSourceConvert } from '@/utils/chart';
    import { message, notification, Modal } from 'ant-design-vue'
    import { propertyFormatByNumber, propertyFormatByPercentage, propertyFormatByDate, parseSubFromDataList } from '@/utils/format';
    import colorTheme from '@/design/custom-theme.json';
    
    import UserTableRecords from '@/model/UserTableRecords';
    import { getAppBaseUrl } from '@/utils/index';
    import { sendToken } from "@/hooks/useIframeToken";
    import { useSystemStore } from "@/store/modules/system";
    const systemStore = useSystemStore();
    



      // 获取传入的流程ID和组件参数
      const props = defineProps({
            'processInstanceId': {
            type: [String,Number,Boolean],
            default: undefined,
        },
      })
      const immediateWatch = (source, callback) => {
        watch(source, callback, {deep: true,immediate: true })
      }



  /* -------------------------- 属性定义 -------------------------- */

      const setTimeOutList = [];
      const pageLoading = reactive({
        loading: false,
        tip: undefined
      });
      const authInfo = localGet('app-user-store');




      // 处理校验
      const setSubFormName =(parentInfo, name)=>{
        return [parentInfo.parents, parentInfo.cycleIndex, name];
      }


  /* ========================== 属性定义 ========================== */


  /* -------------------------- 元素数据引用 -------------------------- */


  /* ========================== 元素数据引用 ========================== */


  /* -------------------------- 页面数据 -------------------------- */


  /* ========================== 页面数据 ========================== */



  /* -------------------------- 响应 -------------------------- */

  /* ========================== 响应 ========================== */


  /* -------------------------- 函数 -------------------------- */

  /* ========================== 函数 ========================== */


  /* -------------------------- 页面参数 -------------------------- */

    const pageParameter_state = reactive({
        'processInstanceId': props.processInstanceId ?? route.query.processInstanceId,
    })

  /* ========================== 页面参数 ========================== */


  /* -------------------------- 组件事件处理方法 -------------------------- */

    // ---------------------------- 组件数据同步 ----------------------------

    // ============================ 组件数据同步 ============================


  /* ========================== 组件事件处理方法 ========================== */


  /* -------------------------- 生命周期 -------------------------- */
  // 用于参数变更后重新执行自定义指令
      const queryUpdateFlag = ref(0);
      onMounted(() => { ;

    });

    onUnmounted(() => {
      // 销毁定时器
      setTimeOutList.forEach(({ repeat, timer }) => {
        repeat ?  clearInterval(timer): clearTimeout(timer);
      });
    });

  /* ========================== 生命周期 ========================== */


  /* -------------------------- 数据关联处理 -------------------------- */





  /* -------------------------- 表单数据同步 -------------------------- */
  /* ========================== 表单数据同步 ========================== */

  /* ========================== 数据关联处理 ========================== */


  /* -------------------------- 不同组件自定义的处理逻辑 -------------------------- */

  /* ========================== 不同组件自定义的处理逻辑 ========================== */


  // ================================定制化逻辑========================================
  onMounted(() => {
          getData()
      })
      function getData() {
          get('/solution-ppm/api/v2/built-in-system-ppm/delay_project/search').then(data => {
              if (data.code !== 200) {
                  message.error(data.message)
                  return
              }
              state.tableData = data.data.delayProjectList
              state.description = data.data.description
              let yq = data.data.delayProjectIndexDetailList.find(item => (item.name = '延期项目总数'))
              state.delayCount = yq
              state.projectData = data.data.delayProjectIndexDetailList.filter(item => item.name !== '延期项目总数')
          })
      }
      const columns = ref([
          {
              title: '区域',
              ellipsis: true,
              resizable: true,
              dataIndex: 'areaName',
              align: 'center'
          },
          {
              title: '项目名称',
              ellipsis: true,
              resizable: true,
              dataIndex: 'projectName',
              align: 'center'
          },
          {
              title: '项目经理',
              ellipsis: true,
              width: 100,
              resizable: true,
              dataIndex: 'pmName',
              align: 'center'
          },
          {
              title: 'PMO',
              ellipsis: true,
              width: 100,
              resizable: true,
              dataIndex: 'pmo',
              align: 'center'
          },
          {
              title: '项目阶段',
              ellipsis: true,
              resizable: true,
              dataIndex: 'milepostName',
              align: 'center'
          },
          {
              title: '计划完成时间',
              ellipsis: true,
              resizable: true,
              width: 150,
              dataIndex: 'planEndTime',
              align: 'center'
          },
          {
              title: '预计完成时间',
              ellipsis: true,
              resizable: true,
              width: 150,
              dataIndex: 'expectEndTime',
              align: 'center'
          },
          {
              title: '延期天数',
              ellipsis: true,
              width: 100,
              resizable: true,
              dataIndex: 'delay',
              align: 'center'
          },
          {
              title: '原因说明',
              resizable: true,
              dataIndex: 'reason',
              width: 400,
              align: 'center'
          }
      ])
      const state = reactive({
          tableData: [],
          projectData: [],
          downLoading: false,
          descriptionVisible: false,
          description: undefined,
          delayCount: {},
          changeDataVisible: false,
          changeReason: undefined
      })
      function handlerGetSpace(data) {
          return data ? data.split(/[,，]/).map(item => item.trim()) : []
      }
      function confirmDescription() {
          put('/solution-ppm/api/v2/built-in-system-ppm/delay_project/remark', { remark: state.description }).then(
              data => {
                  if (data.code !== 200) {
                      message.error(data.message)
                      return
                  }
                  message.success(data.message)
                  state.descriptionVisible = false
                  getData()
              }
          )
      }
      function cancelDescription() {
          state.descriptionVisible = false
      }
      function handleShowDescription() {
          state.descriptionVisible = true
      }
      const handleIssued = async () => {
        state.downLoading = true
          // try {
          //     state.downLoading = true
          //     // 调用接口获取图片的 Base64 数据
          //     const response = await get('/solution-ppm/api/v2/built-in-system-ppm/delay_project/image')
          //     // 检查并去掉 MIME 类型前缀
          //     let base64Data = response.data.split(',')[1]
          //     // 下载图片
          //     downloadImage(base64Data, '水泥配料项目延期项目')
          // } catch (error) {
          //     console.error('下载图片失败：', error)
          //     state.downLoading = false
          // }
          get('/solution-ppm/api/v2/built-in-system-ppm/delay_project/image')
              .then(data => {
                  if (data.code !== 200) {
                      message.error(data.message)
                      return
                  }
                  message.success(data.message)
              })
              .finally(() => {
                  state.downLoading = false
              })
      }

      const downloadImage = (base64, name) => {
          const blob = base64ToBlob(base64)
          const url = URL.createObjectURL(blob)
          const link = document.createElement('a')
          link.href = url
          link.download = `${name}.png` // 设置下载文件名
          link.click()
          URL.revokeObjectURL(url) // 释放 URL 对象
          state.downLoading = false
      }

      const base64ToBlob = base64 => {
          const binary = atob(base64)
          const array = []
          for (let i = 0; i < binary.length; i++) {
              array.push(binary.charCodeAt(i))
          }
          return new Blob([new Uint8Array(array)], { type: 'image/png' })
      }
      const currentData = ref({})
      function changeData(record) {
          currentData.value = record
          state.changeReason = cloneDeep(record.reason)
          state.changeDataVisible = true
      }
      function confirmReason() {
          currentData.value.reason = state.changeReason
          put('/solution-ppm/api/v2/built-in-system-ppm/delay_project/modify', currentData.value).then(data => {
              if (data.code !== 200) {
                  message.error(data.message)
                  return
              }
              message.success(data.message)
              state.changeDataVisible = false
              state.changeReason = undefined
              currentData.value = {}
              getData()
          })
      }
      function cancelReason() {
          state.changeDataVisible = false
          state.changeReason = undefined
          currentData.value = {}
      }
      const overStyle = ref({
          maxWidth: '300px',
          fontSize: '16px'
      })
      function handleResizeColumn(w, col) {
          if (col.title == '原因说明') {
              let div = document.querySelector('.omit-div')
              let width = w - 50
              div.style.width = width + 'px'
              overStyle.value.maxWidth = width + 'px'
          }

          col.width = w
      }
</script>
<style lang="less" scoped>
  .page_root {
  width: 100%;
  height: 100%;
  overflow: auto;
  }
  .page_root :deep(.@{ant-prefix}-spin-nested-loading),
  .page_root :deep(.@{ant-prefix}-spin-container)
   {
      height: 100%;
  }
  .page_root :deep(.@{ant-prefix}-spin-container .@{ant-prefix}-table-wrapper)
   {
      display: flex;
      flex-flow: column nowrap;
      justify-content: flex-start;
  }
  .page_root :deep(.@{ant-prefix}-table)
   {
    flex: auto;
    overflow: auto;
  }
  .table-moreBtn_down {
    overflow: hidden; white-space: nowrap; text-overflow: ellipsis; width: 100px;
  }

  .table-moreBtn_menu :deep(.table-moreBtn_menu-item):hover {
    background: #ebf1ff;
  }

  /*  表格树结构样式处理，展开按钮层级增加*/
  :deep(.@{ant-prefix}-table-row-expand-icon) {
    z-index: 1;
  }
  /*  表格树结构 由于每个表格项采用自定义组件，使用绝对定位布局，开启树结构导致显示异常，暂时使用层级定位位置 */
  :deep(.@{ant-prefix}-table-row-level-1 .@{ant-prefix}-table-cell-with-append .cell-wrapper-left) {
    left: 15px !important;
    width: calc(100% - 15px);
  }
  :deep(.@{ant-prefix}-table-row-level-2 .@{ant-prefix}-table-cell-with-append .cell-wrapper-left) {
    left: 30px !important;
    width: calc(100% - 30px);
  }
  :deep(.@{ant-prefix}-table-row-level-3 .@{ant-prefix}-table-cell-with-append .cell-wrapper-left) {
    left: 45px !important;
    width: calc(100% - 45px);
  }
  :deep(.@{ant-prefix}-table-row-level-4 .@{ant-prefix}-table-cell-with-append .cell-wrapper-left) {
    left: 60px !important;
    width: calc(100% - 60px);
  }

  /* 穿梭框改变默认样式，为根据组件样式控制左右栏宽度。 */
  :deep(.@{ant-prefix}-transfer-list)
   {
      height: 100%;
      width: 50%;
  }


  /*样式*/
      .default-table:deep(.@{ant-prefix}-table-thead) > tr > th {
          background-color: #3875ff;
          color: #fff;
          font-weight: 600;
          padding: 8px 16px;
          border-right: 1px solid #d9d9d9;
      }
      .default-table :deep(.@{ant-prefix}-table-tbody) tr > td {
          font-size: 14px;
          font-family: arial, helvetica, 'microsoft yahei';
          font-weight: 400;
          color: #595959;
          border-bottom: 1px solid #d9d9d9;
          padding: 8px 16px;
          word-break: break-all;

          .cell-wrapper {
              padding: 0 16px;
          }
      }
      .default-table :deep(.ant3-table-wrapper) {
        border-bottom: 1px solid #d9d9d9;
      }
      .top-title {
          height: 16px;
          padding-left: 8px;
          border-left: 4px solid #3875ff;
          font-size: 16px;
          line-height: 16px;
          color: #262626;
          font-weight: 600;
      }
      /*样式*/
      .title {
          justify-content: space-between;
          display: flex;
          margin-bottom: 16px;
          align-items: center;
          font-weight: bold; /* 标题加粗 */
          height: 70px;
          border-bottom: 1px solid #d9d9d9;
      }
      .content {
          display: flex;
          gap: 16px;
          margin-bottom: 16px;
      }
      .left {
          width: 100%;
      }
      .right {
          flex: 1;
      }
      .description {
          padding: 12px 16px;
          border: 1px solid #d9d9d9;
          word-wrap: break-word; /* 强制换行 */
          overflow-wrap: break-word; /* 支持较旧浏览器 */
          white-space: pre-wrap; /* 保持换行符 */
          max-height: 80px;
          min-height: 80px;
          overflow: auto;
          border-radius: 4px;
      }
      .body {
          height: 100%;
          background-color: #fff;
          padding: 24px;
          padding-top: 0;
      }

      .title-margin {
          display: flex;
          align-items: center;
          font-size: 16px;
          color: #262626;
          letter-spacing: 0;
          margin-bottom: 13px;
      }
      .left-content {
          width: 100%; /* 大 div 的宽度 */
          height: 80px;
          display: flex;
          gap: 8px;
      }

      .scroll-container {
          padding: 16px 0px;
          flex: 1;
          display: inline-flex; /* 使用 inline-flex 确保横向排列 */
          white-space: nowrap; /* 防止换行 */
          height: 100%;
          overflow: auto;
          background: #ebf1ff;
          border: 1px solid #3875ff;
          border-radius: 4px;
      }

      .content-item {
          width: 125px;
          display: inline-block; /* 保证小 div 不换行 */
          border-right: 1px solid #a4c0ff; /* 边框样式 */
          box-sizing: border-box; /* 包括内边距和边框在内的宽度计算 */
          padding: 0 10px;
      }
      .content-item:last-child {
          border: none;
      }

      .number {
          text-align: center;
          font-size: 20px;
          color: #262626;
          letter-spacing: 0;
          font-weight: 500;
          height: 24px;
          line-height: 24px;
      }
      .title-content {
          height: 24px;
          line-height: 24px;
          width: 100%;
          text-align: center; /* 如果希望文字居中显示 */
          font-size: 14px;
          color: #595959;
          letter-spacing: 0;
          overflow: hidden;
          text-overflow: ellipsis;
          white-space: nowrap;
          display: block;
      }
      .scroll-container::-webkit-scrollbar {
          height: 4px; /* 设置滚动条的高度 */
      }
      .zb-img,
      .ms-img {
          margin-right: 4px;
          width: 16px;
          height: 16px;
      }
      .zb-img {
          background-image: url('@/assets/images/b430622b78ac3ae3fd1838321ea50be8.png');
          background-size: cover;
      }
      .ms-img {
          background-image: url('@/assets/images/483fd70f25cb2a4a42e0a0cbb8ade9dd.png');
          background-size: cover;
      }
      .yq-div {
          flex-direction: column; /* 确保子元素纵向排列 */
          padding: 16px;
          width: 120px;
          background: #ebf1ff;
          border: 1px solid #3875ff;
          border-radius: 4px;
          display: flex;
      }
      .text-line-div {
        text-decoration: underline;
        position: relative;
      }

      .db-click {
        cursor: pointer;
      }
      .red-color{
        color: #F5222D;
      }
      .omit-div {
        width: 320px;
        padding: 0 8px;
        min-height: 20px;
        height: 120px;
        white-space: pre-wrap;
        word-wrap: break-word;
        cursor: pointer;
        overflow: hidden;
        text-overflow: ellipsis;
        display: -webkit-box;
        -webkit-line-clamp: 4; /* 显示行数 */
        -webkit-box-orient: vertical;
      }
</style>